// 游戏常量
const COLS = 10;
const ROWS = 20;
const BLOCK_SIZE = 20;
const COLORS = [
    null,
    '#00F7FF', // I - 青色
    '#9400FF', // J - 紫色
    '#FF00A0', // L - 粉红
    '#00FFC3', // O - 蓝绿
    '#FF00FF', // S - 品红
    '#FF7B00', // T - 橙色
    '#00FF57'  // Z - 绿色
];

// 方块形状定义
const SHAPES = [
    null,
    [[0,0,0,0],[1,1,1,1],[0,0,0,0],[0,0,0,0]], // I
    [[2,0,0],[2,2,2],[0,0,0]], // J
    [[0,0,3],[3,3,3],[0,0,0]], // L
    [[0,4,4],[0,4,4],[0,0,0]], // O
    [[0,5,5],[5,5,0],[0,0,0]], // S
    [[0,6,0],[6,6,6],[0,0,0]], // T
    [[7,7,0],[0,7,7],[0,0,0]]  // Z
];

// 游戏状态
let board = createMatrix(COLS, ROWS);
let piece = { pos: {x:0,y:0}, matrix:null, type:null };
let score = 0;
let level = 1;
let gameOver = false;
let isPaused = false;
let dropCounter = 0;
let dropInterval = 1000;
let lastTime = 0;
let animationId = null;
let boardChanged = true;

// 获取Canvas元素
const canvas = document.getElementById('game-board');
const ctx = canvas.getContext('2d');
const nextCanvas = document.getElementById('next-piece');
const nextCtx = nextCanvas.getContext('2d');

// 离屏渲染
const offscreenCanvas = document.createElement('canvas');
offscreenCanvas.width = canvas.width;
offscreenCanvas.height = canvas.height;
const offCtx = offscreenCanvas.getContext('2d');

// 创建矩阵
function createMatrix(width, height) {
    const matrix = [];
    for (let i = 0; i < height; i++) {
        matrix.push(new Array(width).fill(0));
    }
    return matrix;
}

// 绘制矩阵
function drawMatrix(ctx, matrix, offset, isGhost = false) {
    matrix.forEach((row, y) => {
        row.forEach((value, x) => {
            if (value !== 0) {
                const posX = (x + offset.x) * BLOCK_SIZE;
                const posY = (y + offset.y) * BLOCK_SIZE;
                
                if (!isGhost) {
                    ctx.shadowColor = COLORS[value];
                    ctx.shadowBlur = 15;
                    ctx.fillStyle = COLORS[value];
                    ctx.fillRect(posX, posY, BLOCK_SIZE, BLOCK_SIZE);
                    ctx.shadowColor = 'transparent';
                } else {
                    ctx.globalAlpha = 0.3;
                    ctx.fillStyle = COLORS[value];
                    ctx.fillRect(posX, posY, BLOCK_SIZE, BLOCK_SIZE);
                    ctx.globalAlpha = 1.0;
                }
            }
        });
    });
}

// 绘制游戏板
function draw() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    if (boardChanged) {
        offCtx.fillStyle = '#111';
        offCtx.fillRect(0, 0, canvas.width, canvas.height);
        drawMatrix(offCtx, board, {x:0,y:0});
        boardChanged = false;
    }
    
    ctx.drawImage(offscreenCanvas, 0, 0);
    drawMatrix(ctx, piece.matrix, piece.pos);
    drawGhostPiece();
}

// 绘制幽灵方块
function drawGhostPiece() {
    const ghost = {...piece};
    while (!collide(ghost.matrix, {x: ghost.pos.x, y: ghost.pos.y + 1})) {
        ghost.pos.y++;
    }
    drawMatrix(ctx, ghost.matrix, ghost.pos, true);
}

// 绘制下一个方块
function drawNextPiece() {
    nextCtx.clearRect(0, 0, nextCanvas.width, nextCanvas.height);
    const nextType = Math.floor(Math.random() * 7) + 1;
    const nextMatrix = SHAPES[nextType];
    
    nextCtx.fillStyle = COLORS[nextType];
    for (let y = 0; y < nextMatrix.length; y++) {
        for (let x = 0; x < nextMatrix[y].length; x++) {
            if (nextMatrix[y][x]) {
                nextCtx.fillRect(x * 20, y * 20, 20, 20);
            }
        }
    }
}

// 创建新方块
function createPiece() {
    const type = Math.floor(Math.random() * 7) + 1;
    piece.matrix = SHAPES[type];
    piece.type = type;
    piece.pos.y = 0;
    piece.pos.x = Math.floor(COLS / 2) - Math.floor(piece.matrix[0].length / 2);
    
    if (collide()) {
        handleGameOver();
    }
}

// 碰撞检测
function collide(matrix = piece.matrix, pos = piece.pos) {
    for (let y = 0; y < matrix.length; y++) {
        for (let x = 0; x < matrix[y].length; x++) {
            if (matrix[y][x] !== 0 &&
                (board[y + pos.y] &&
                 board[y + pos.y][x + pos.x]) !== 0) {
                return true;
            }
        }
    }
    return false;
}

// 合并方块到游戏板
function merge() {
    piece.matrix.forEach((row, y) => {
        row.forEach((value, x) => {
            if (value !== 0) {
                board[y + piece.pos.y][x + piece.pos.x] = value;
            }
        });
    });
    boardChanged = true;
}

// 消除已填满的行
function clearLines() {
    let linesCleared = 0;
    
    outer: for (let y = board.length - 1; y >= 0; y--) {
        for (let x = 0; x < board[y].length; x++) {
            if (board[y][x] === 0) {
                continue outer;
            }
        }
        
        const row = board.splice(y, 1)[0].fill(0);
        board.unshift(row);
        y++;
        linesCleared++;
    }
    
    if (linesCleared > 0) {
        score += linesCleared * 100 * level;
        level = Math.floor(score / 1000) + 1;
        dropInterval = 1000 / level;
        updateScore();
        playSound('clear-sound');
    }
}

// 更新分数显示
function updateScore() {
    document.getElementById('score').textContent = score;
    document.getElementById('level').textContent = level;
}

// 游戏结束处理
function handleGameOver() {
    if (!gameOver) {
        gameOver = true;
        playSound('gameover-sound');
        document.getElementById('game-start-overlay').style.display = 'flex';
        document.getElementById('game-start-overlay').innerHTML = `
            <h2>游戏结束</h2>
            <p>最终得分: ${score}</p>
            <button onclick="startGame()">再玩一次</button>
        `;
    }
}

// 游戏主循环
function gameLoop(time = 0) {
    if (isPaused || gameOver) return;
    
    const deltaTime = time - lastTime;
    lastTime = time;
    
    dropCounter += deltaTime;
    if (dropCounter > dropInterval) {
        moveDown();
        dropCounter = 0;
    }
    
    draw();
    drawNextPiece();
    
    animationId = window.requestAnimationFrame(gameLoop);
}

// 方块控制
function moveDown() {
    piece.pos.y++;
    if (collide()) {
        piece.pos.y--;
        merge();
        clearLines();
        createPiece();
    } else {
        playSound('move-sound');
    }
}

function moveLeft() {
    piece.pos.x--;
    if (collide()) {
        piece.pos.x++;
    } else {
        playSound('move-sound');
    }
}

function moveRight() {
    piece.pos.x++;
    if (collide()) {
        piece.pos.x--;
    } else {
        playSound('move-sound');
    }
}

function rotate() {
    const matrix = piece.matrix;
    const N = matrix.length;
    const originalMatrix = matrix.map(row => [...row]);
    
    // 转置矩阵
    for (let y = 0; y < N; y++) {
        for (let x = 0; x < y; x++) {
            [matrix[x][y], matrix[y][x]] = [matrix[y][x], matrix[x][y]];
        }
    }
    
    // 反转每行
    for (let y = 0; y < N; y++) {
        matrix[y].reverse();
    }
    
    if (collide()) {
        // 恢复原状
        for (let y = 0; y < N; y++) {
            matrix[y].reverse();
        }
        for (let y = 0; y < N; y++) {
            for (let x = 0; x < y; x++) {
                [matrix[x][y], matrix[y][x]] = [matrix[y][x], matrix[x][y]];
            }
        }
    } else {
        playSound('rotate-sound');
    }
}

// 开始游戏
function startGame() {
    document.getElementById('game-start-overlay').style.display = 'none';
    document.getElementById('game-container').style.display = 'flex';
    document.getElementById('start-btn').disabled = true;
    document.getElementById('pause-btn').disabled = false;
    document.getElementById('reset-btn').disabled = false;
    
    board = createMatrix(COLS, ROWS);
    score = 0;
    level = 1;
    gameOver = false;
    isPaused = false;
    dropInterval = 1000;
    boardChanged = true;
    
    updateScore();
    createPiece();
    lastTime = performance.now();
    gameLoop();
}

// 暂停/继续游戏
function togglePause() {
    isPaused = !isPaused;
    if (!isPaused && !gameOver) {
        lastTime = performance.now();
        gameLoop();
    }
    document.getElementById('pause-btn').textContent = isPaused ? '继续' : '暂停';
}

// 重新开始游戏
function resetGame() {
    cancelAnimationFrame(animationId);
    startGame();
}

// 全屏切换
function toggleFullscreen() {
    if (!document.fullscreenElement) {
        document.documentElement.requestFullscreen();
    } else {
        document.exitFullscreen();
    }
}

// 播放音效
function playSound(id) {
    try {
        const sound = document.getElementById(id);
        if (sound) {
            sound.currentTime = 0;
            sound.play().catch(e => console.log('音效播放失败:', e));
        }
    } catch (e) {
        console.log('音效错误:', e);
    }
}

// 键盘控制
function setupControls() {
    document.addEventListener('keydown', event => {
        if (gameOver) return;
        
        switch (event.keyCode) {
            case 37: // 左箭头
                moveLeft();
                break;
            case 39: // 右箭头
                moveRight();
                break;
            case 40: // 下箭头
                moveDown();
                break;
            case 38: // 上箭头
                rotate();
                break;
            case 32: // 空格键
                while (!collide()) {
                    piece.pos.y++;
                }
                piece.pos.y--;
                merge();
                clearLines();
                createPiece();
                break;
        }
    });
}

// 初始化游戏
function init() {
    document.getElementById('start-btn').addEventListener('click', startGame);
    document.getElementById('pause-btn').addEventListener('click', togglePause);
    document.getElementById('reset-btn').addEventListener('click', resetGame);
    document.getElementById('fullscreen-btn').addEventListener('click', toggleFullscreen);
    
    document.getElementById('game-container').style.display = 'none';
    document.getElementById('game-start-overlay').style.display = 'flex';
    
    setupControls();
}

window.addEventListener('DOMContentLoaded', init);